#!/bin/bash
# Ambari Cluster Start Script
# Usage: ./ambari-start-cluster.sh

set -e

# 配置参数
AMBARI_SERVER="hadoop-app"
SSH_USER="root"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# 检查SSH连接
check_ssh() {
    local host=$1
    if ssh $SSH_OPTS $SSH_USER@$host "TERM=dumb && echo SSH连接成功" &>/dev/null; then
        log_info "SSH连接 $host 成功"
        return 0
    else
        log_error "SSH连接 $host 失败"
        return 1
    fi
}

# 启动Ambari Server
start_ambari_server() {
    log_info "正在启动Ambari Server ($AMBARI_SERVER)..."
    if ssh $SSH_OPTS $SSH_USER@$AMBARI_SERVER "TERM=dumb && ambari-server start" &>/dev/null; then
        log_info "Ambari Server 启动成功"
    else
        log_error "Ambari Server 启动失败"
        exit 1
    fi
}

# 启动Ambari Agents
start_ambari_agents() {
    local hosts=("hadoop-node1" "hadoop-node2" "hadoop-node3")
    
    for host in "${hosts[@]}"; do
        log_info "正在启动Ambari Agent ($host)..."
        if ssh $SSH_OPTS $SSH_USER@$host "TERM=dumb && ambari-agent start" &>/dev/null; then
            log_info "Ambari Agent $host 启动成功"
        else
            log_warn "Ambari Agent $host 启动失败"
        fi
    done
}

# 检查服务状态
check_services_status() {
    log_info "等待服务启动..."
    sleep 10
    
    log_info "检查Ambari Server状态:"
    ssh $SSH_OPTS $SSH_USER@$AMBARI_SERVER "TERM=dumb && ambari-server status"
    
    log_info "检查Ambari Agents状态:"
    local hosts=("hadoop-node1" "hadoop-node2" "hadoop-node3")
    for host in "${hosts[@]}"; do
        echo "=== $host ==="
        ssh $SSH_OPTS $SSH_USER@$host "TERM=dumb && ambari-agent status" || true
    done
}

# 主函数
main() {
    log_info "开始启动Ambari集群..."
    
    # 检查Ambari Server SSH连接
    check_ssh $AMBARI_SERVER || exit 1
    
    # 启动Ambari Server
    start_ambari_server
    
    # 启动所有Ambari Agents
    start_ambari_agents
    
    # 检查服务状态
    check_services_status
    
    log_info "Ambari集群启动完成!"
    log_info "Ambari Web界面: http://$AMBARI_SERVER:8080"
    log_info "默认用户名/密码: admin/admin"
}

main "$@"
